package cn.stylefeng.guns.sys.modular.system.service.impl;

import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.sys.modular.system.entity.BtyDysk;
import cn.stylefeng.guns.sys.modular.system.entity.Yybb;
import cn.stylefeng.guns.sys.modular.system.mapper.BtyDyskMapper;
import cn.stylefeng.guns.sys.modular.system.model.params.BtyDyskParam;
import cn.stylefeng.guns.sys.modular.system.model.result.BtyDyskResult;
import  cn.stylefeng.guns.sys.modular.system.service.BtyDyskService;
import cn.stylefeng.guns.sys.modular.system.service.YybbService;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.InputStream;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author liuy
 * @since 2021-12-16
 */
@Service
public class BtyDyskServiceImpl extends ServiceImpl<BtyDyskMapper, BtyDysk> implements BtyDyskService {
    @Resource
    private YybbService yybbService;
    @Override
    public void add(BtyDyskParam param){
        BtyDysk entity = getEntity(param);
        this.save(entity);
    }

    @Override
    public void delete(BtyDyskParam param){
        this.removeById(getKey(param));
    }

    @Override
    public void update(BtyDyskParam param){
        BtyDysk oldEntity = getOldEntity(param);
        BtyDysk newEntity = getEntity(param);
        ToolUtil.copyProperties(newEntity, oldEntity);
        this.updateById(newEntity);
    }
    /**
     * 导入excel
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean batchImport(String fileName, MultipartFile file, BtyDyskParam param){
        boolean notNull = false;
        try {
            if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
                throw new Exception("上传文件格式不正确");
            }
            boolean isExcel2003 = true;
            if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
                isExcel2003 = false;
            }
            InputStream is = file.getInputStream();
            Workbook wb = null;
            if (isExcel2003) {
                wb = new HSSFWorkbook(is);
            } else {
                wb = new XSSFWorkbook(is);
            }
            //excel中多个sheet表，获取所有sheet表的数量
            //int sheets = wb.getNumberOfSheets();
            //System.out.println("sheets:"+sheets);
            //导入之前删掉之前的数据
            baseMapper.delete(new QueryWrapper<>());
            for (int i = 0; i < 1; i++) {
                //Sheet sheet = wb.getSheetAt(i);
                Sheet sheet = wb.getSheetAt(0);
                if (sheet != null) {
                    notNull = true;
                }

                int lastRowNum = sheet.getLastRowNum();
                for (int r = 1; r <= lastRowNum; r++) {
                    Row row = sheet.getRow(r);
                    if (row == null) {
                        continue;
                    }
                    //获取单元格
                    Cell cell0 = row.getCell(5);
                    if (ToolUtil.isNotEmpty(cell0)) {
                        cell0.setCellType(CellType.STRING);
                    }
                    Cell cell = row.getCell(8);
                    if (ToolUtil.isNotEmpty(cell)) {
                        cell.setCellType(CellType.STRING);
                    }
                    Cell cell6 = row.getCell(11);
                    if (ToolUtil.isNotEmpty(cell6)) {
                        cell6.setCellType(CellType.STRING);
                    }
                    //核销时间
                    String hxsj=row.getCell(0) == null ? "" : row.getCell(0).getStringCellValue();
                    System.out.println("hxsj:"+hxsj);
                    if(ToolUtil.isNotEmpty(hxsj)&&hxsj.length()>9){
                        hxsj=hxsj.substring(0,10);
                    }

                    String tgmc=row.getCell(1) == null ? "" : row.getCell(1).getStringCellValue();
                    //营业额
                    String yye = row.getCell(4) == null ? "" : row.getCell(4).getStringCellValue();
                    //手续费
                    String sxf = row.getCell(8) == null ? "" : row.getCell(8).getStringCellValue();
                    //到账金额
                    String dzje = row.getCell(11) == null ? "" : row.getCell(11).getStringCellValue();
                    //核销门店
                    String dm = row.getCell(12) == null ?"" : row.getCell(12).getStringCellValue();
                    //门店id
                    String mdid = row.getCell(13) == null ?"" : row.getCell(13).getStringCellValue();
                    BtyDysk dysk=new BtyDysk();
                    dysk.setHxsj(hxsj);
                    dysk.setTgmc(tgmc);
                    dysk.setYye(new BigDecimal(yye).setScale(2, BigDecimal.ROUND_HALF_UP));
                    dysk.setSxf(new BigDecimal(sxf).setScale(2, BigDecimal.ROUND_HALF_UP));
                    dysk.setDzje(new BigDecimal(dzje).setScale(2, BigDecimal.ROUND_HALF_UP));
                    dysk.setMdid(mdid);
                    dysk.setHxmd(dm);
                    baseMapper.insert(dysk);
                }

                //导入成功之后更新抖音收款金额到yybb中
                List<BtyDyskResult> list=baseMapper.dmList(3);
                if(list.size()>0){
                    for (BtyDyskResult dyskResult : list) {
                        String yyr=dyskResult.getHxsj();
                        String dm=dyskResult.getDm();
                        String dydm=dyskResult.getHxmd();
                        BigDecimal dysk=dyskResult.getDzje();
                        BigDecimal yye=dyskResult.getYye();
                        BigDecimal sxf=dyskResult.getSxf();
                        Yybb yybb=yybbService.getOne(new QueryWrapper<Yybb>().eq("dianming",dm).eq("yyr",yyr));
                        if(ToolUtil.isNotEmpty(yybb)){
                            if(ToolUtil.isNotEmpty(yybb.getDy())){
                              yybb.setDy(yybb.getDy().add(dysk));
                            }else {
                                yybb.setDy(dysk);
                            }
                            if(ToolUtil.isNotEmpty(yybb.getDyyye())){
                                yybb.setDyyye(yybb.getDyyye().add(yye));
                            }else {
                                yybb.setDyyye(yye);
                            }
                            if(ToolUtil.isNotEmpty(yybb.getDysxf())){
                                yybb.setDysxf(yybb.getDysxf().add(sxf));
                            }else {
                                yybb.setDysxf(sxf);
                            }
                            yybbService.updateById(yybb);
                            BtyDyskParam param1=new BtyDyskParam();
                            param1.setHxmd(dydm);
                            baseMapper.updateByMdid(param1);
                        }
                    }
                }
            }
        } catch (Exception e) {
            notNull=false;
            e.printStackTrace();
        }
        return notNull;
    }

    @Override
    public BtyDyskResult findBySpec(BtyDyskParam param){
        return null;
    }

    @Override
    public List<BtyDyskResult> findListBySpec(BtyDyskParam param){
        return baseMapper.customList(param);
    }

    @Override
    public LayuiPageInfo findPageBySpec(BtyDyskParam param){
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.customPageList(pageContext, param);
        return LayuiPageFactory.createPageInfo(page);
    }

    private Serializable getKey(BtyDyskParam param){
        return param.getId();
    }

    private Page getPageContext() {
        return LayuiPageFactory.defaultPage();
    }

    private BtyDysk getOldEntity(BtyDyskParam param) {
        return this.getById(getKey(param));
    }

    private BtyDysk getEntity(BtyDyskParam param) {
        BtyDysk entity = new BtyDysk();
        ToolUtil.copyProperties(param, entity);
        return entity;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean insertDysk(List<BtyDysk> sub) {
        return baseMapper.insertDysk(sub);
    }

    @Override
    public List<BtyDyskResult> dmList(Integer state) {
        return baseMapper.dmList(state);
    }

}
